package com.bonc.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl;
import oracle.jdbc.OracleConnection;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author jinlong
 * @date 2021/7/20
 */
public class DataSourceUtils {
    /**
     * 获取数据库中所有的表名称
     *
     * @param conn 数据库的连接
     * @return 该数据库中所有的表名称
     * @throws SQLException
     */
    public static List<String> getTables(Connection conn) throws SQLException {
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet resultSet = metaData.getTables(conn.getCatalog(), "%", null, new String[]{"TABLE"});
        List<String> tables = new ArrayList<>();
        while (resultSet.next()) {
            String tableName = resultSet.getString("TABLE_NAME");
            tables.add(tableName);
        }
        return tables;
    }

    /**
     * 获取指定表的所有字段名称
     *
     * @param conn      数据库连接
     * @param tableName 表名称
     * @return 该表所有的字段名称(小写)
     * @throws SQLException
     */
    public static Map<String, String> getColumns(Connection conn, String tableName) throws SQLException {
        if (conn instanceof DruidPooledConnection) {
            //ConnectionProxyImpl connectionProxy = (ConnectionProxyImpl) ((DruidPooledConnection) conn).getConnection();
            //conn = connectionProxy.getConnectionRaw();
            conn = ((DruidPooledConnection) conn).getConnection();
            //设置Oracle数据库的表注释可读
            //设置连接属性,使得可获取到表的REMARK(备注)
            if (conn instanceof OracleConnection) {
                ((OracleConnection) conn).setRemarksReporting(true);
            }
        }
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet rs = metaData.getColumns(conn.getCatalog(), null, tableName, null);
        List<String> columnNames = new ArrayList<>();
        List<String> remarks = new ArrayList<>();
        while (rs.next()) {
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            String columnName = rs.getString("COLUMN_NAME");
            String remark = rs.getString("REMARKS");
            columnNames.add(columnName);
            remarks.add(remark);
        }

        return CollUtil.zip(columnNames, remarks);
    }

}
